﻿using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;

namespace MyClass_StringProcess
{
    public class String_Hex_Exchange
    {
        //将带有十六进制数的字符串 转换为byte[] 数组 例如“1A 2B 3C 21”->{0x1A, 0x2B, 0x3C, 0x21}
        public static byte[] Str2Hex(string Str)
        {
            int i = 0;
            string HexStr = Str.Replace(" ", "");
            int len = HexStr.Length;
            byte[] Return_Arr = new byte[len / 2];
            string TempStr;

            while (len > 1)
            {
                len -= 2;
                TempStr = HexStr.Substring(i * 2, 2);
                Return_Arr[i++] = Convert.ToByte(TempStr, 16);
            }
            return Return_Arr;
        }
        //将字符串中的数字 转换为byte[] 数组  例如“16051120”-》{16,05,11,20}
        public static byte[] Str2Byte(string Str)
        {
            int i = 0;
            string HexStr = Str.Replace(" ", "");
            int len = HexStr.Length;
            byte[] Return_Arr = new byte[len / 2];
            string TempStr;

            while (len > 1)
            {
                len -= 2;
                TempStr = HexStr.Substring(i * 2, 2);
                Return_Arr[i++] = Convert.ToByte(TempStr);
            }
            return Return_Arr;
        }
        //将byte[] 数组转换为带有十六进制数 的字符串 例如 {0x1A, 0x2B, 0x3C, 0x21}->“1A 2B 3C 21”
        public string Hex2Str(byte[] tempChar)
        {
            int i = 0;
            int len = tempChar.Length;
            string Return_Arr = "";

            while (len > 0)
            {
                len -= 1;
                Return_Arr += tempChar[i++].ToString("X2") + " ";
            }
            return Return_Arr + "\n";
        }
    }
}
